/**
 * @description: 数据加密
 * @author: lxz
 * @update: lxz(2021-01-18)
 */

import CryptoJS from '@/global/scripts/libs/crypto-js.min'
import JSEncrypt from '@/global/scripts/libs/jsencrypt.min'
import { getRandomStr } from '@utils/base/string'

// rsa加密公钥, rsa解密私钥
const { PUBLIC_KEY, PRIVATE_KEY } = $config
// rsa加解密
const rsa = {
	encrypt(data) {
		if (!data) {
			console.log('数据为空')
			return
		}
		// 使用公钥加密
		const encrypt = new JSEncrypt()
		encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + PUBLIC_KEY + '-----END PUBLIC KEY-----')
		// 返回密文
		return encrypt.encrypt(typeof data === 'object' ? JSON.stringify(data) : data.toString())
	},
	decrypt(str) {
		if (typeof str !== 'string') {
			console.log('传入数据有误')
			return
		}
		// 使用私钥解密
		const decrypt = new JSEncrypt()
		decrypt.setPrivateKey('-----BEGIN RSA PRIVATE KEY-----' + PRIVATE_KEY + '-----END RSA PRIVATE KEY-----')
		// 还原回对象形式
		let data = decrypt.decrypt(str)
		try {
			data = JSON.parse(data)
		} catch (error) {}
		// 返回数据
		return data
	}
}
// aes加解密
const aes = {
	encrypt(data, key) {
		const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412')
		const srcs = CryptoJS.enc.Utf8.parse(typeof data === 'object' ? JSON.stringify(data) : data.toString())
		const encrypted = CryptoJS.AES.encrypt(srcs, CryptoJS.enc.Utf8.parse(key), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, iv })
		return encrypted.toString()
	},
	decrypt(str, key) {
		const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412')
		const decrypt = CryptoJS.AES.decrypt(str, CryptoJS.enc.Utf8.parse(key), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, iv })
		let data = CryptoJS.enc.Utf8.stringify(decrypt).toString()
		try {
			data = JSON.parse(data)
		} catch (error) {}
		return data
	}
}

// 混合加密
export function encrypt(data) {
	const key = getRandomStr()
	return {
		key: rsa.encrypt(key),
		val: aes.encrypt(data, key)
	}
}
// 混合解密
export function decrypt(data) {
	return aes.decrypt(data.val, rsa.decrypt(data.key))
}
